# -*- coding: UTF-8 -*-
"""
    @Project ：taobao
    @File ：taobao.py
    @Author ：lc
    @Date ：2022/8/28 18:58
"""
import datetime
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


def login(browser_driver):
    """
    登录淘宝
    :param browser_driver: 驱动
    :return: 无
    """
    # 点击登录
    browser_driver.find_element(By.XPATH, "//div[@class='cover J_Cover']/div/div/ul/li[2]/div/div/a[1]").click()
    time.sleep(2)
    # 点击扫描登录
    browser_driver.find_element(By.XPATH, "//i[@class='iconfont icon-qrcode']").click()
    time.sleep(10)


def time_compare(my_time):
    """
    等待抢购时间
    :param my_time: 抢购时间
    :return: 无
    """
    while 1:
        now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
        print("当前时间：", now_time)
        print("等待抢购时间:", my_time)
        if now_time > my_time:
            print("抢购成功!!!", end="\n")
            print("抢购点击时间：", now_time)
            break


def buy(browser_driver, my_time, my_cart_num):
    """
    锁定商品
    :param browser_driver: 驱动
    :param my_time: 抢购时间
    :param my_cart_num: 购物车店铺排序
    :return: 无
    """
    # 进入购物车
    browser_driver.find_element(By.XPATH, "//ul[@id='J_SiteNavBdR']/li[3]/div/a").click()
    time.sleep(3)
    # 选中购物车第一个店铺
    browser_driver.find_element(By.XPATH, f"//div[@id='J_OrderList']/div[{my_cart_num}]/div/div/div/div").click()
    # 等待抢购时间
    time_compare(my_time)
    # 进入结算界面
    browser_driver.find_element(By.XPATH, "//div[@class='btn-area']/a").click()
    print("点击进如结算界面")
    browser_driver.execute_script("window.scrollTo(0,500)")
    submit_element = WebDriverWait(browser_driver, 3).until(
        lambda x: x.find_element(By.XPATH, "//div[@class='submitOrder-container']/div/a[2]"))
    if submit_element:
        submit_element.click()
    time.sleep(2)


# 抢购时间
buy_time = '2022-08-29 10:00:00.000000'
# 购物车店铺排序
cart_num = 1
driver = webdriver.Chrome()
driver.get("https://www.taobao.com/")
driver.maximize_window()
login(driver)
buy(driver, buy_time, cart_num)
